package com.eschool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eschool.mapper.ClassRoomMapper;
import com.eschool.mapper.ClassRoomOccupyMapper;
import com.eschool.pojo.ClassRoomDAO;
import com.eschool.pojo.FindRoomDTO;
import com.eschool.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoomServiceImpl implements RoomService {
    @Autowired
    ClassRoomMapper classRoomMapper;
    @Autowired
    ClassRoomOccupyMapper classRoomOccupyMapper;


    @Override
    public List<ClassRoomDAO> FindRoom(FindRoomDTO findRoomDTO) {
        QueryWrapper<ClassRoomDAO> queryWrapper = new QueryWrapper<>();
        if (findRoomDTO.getScale() != null) {
            queryWrapper.eq("scale", findRoomDTO.getScale());
        }
        if (findRoomDTO.getComputer() != null) {
            queryWrapper.eq("computer", findRoomDTO.getComputer());
        }
        if (findRoomDTO.getAircon() != null) {
            queryWrapper.eq("aircon", findRoomDTO.getAircon());
        }

        // 2. 添加时间冲突排除条件（跨表子查询）
        if (findRoomDTO.getWeekday() != null
                && findRoomDTO.getStartTime()!= null
                && findRoomDTO.getEndTime() != null) {

            // 子查询逻辑：检查是否存在冲突的占用记录
            queryWrapper.notExists(
                    "SELECT 1 FROM classroom_occupy co " +
                            "WHERE co.roomid = classroom.roomid " + // 关键：跨表关联 roomid
                            "AND co.weekday = {0} " +
                            "AND co.start_time <= {1} " +
                            "AND co.end_time >= {2}",
                    findRoomDTO.getWeekday(),
                    findRoomDTO.getStartTime(),
                    findRoomDTO.getEndTime()
            );
        }

        // 3. 单次查询直接返回最终结果
        return classRoomMapper.selectList(queryWrapper);

    }
}
